﻿using Shape.Mvp;
using Shape.Mvp.Events;
using Shape.Mvp.Presenters;
using SimpleTasks.Domain.Model;
using SimpleTasks.Domain.Repositories;
using SimpleTasks.Events;
using SimpleTasks.Persistence;
using SimpleTasks.Views;
using System;
using System.Linq;

namespace SimpleTasks.Presenters
{
   public class SimpleTaskListPresenter : Presenter<ISimpleTaskListView>,
                                          ISubscriber<SimpleTaskCreatedEvent>
   {
      #region Fields
      private IUnitOfWork _currentUnitOfWork;
      private IRepository<SimpleTask> _simpleTaskRepository;
      #endregion
      
      #region Constructor(s)
      public SimpleTaskListPresenter(IApplicationController applicationController,
                                     IUnitOfWork unitOfWork,
                                     IRepository<SimpleTask> simpleTaskRepository,
                                     ISimpleTaskListView view)
         : base(applicationController, view)
      {
         _currentUnitOfWork = unitOfWork;
         _simpleTaskRepository = simpleTaskRepository;
      }
      #endregion

      #region Public Interface
      public void Initialise()
      {
         ApplicationController.AddEventSubscriber(this);

         _currentUnitOfWork.Resume();

         try
         {
            foreach (var item in _simpleTaskRepository.Query())
            {
               View.Add(item.Id, item.Description);
            }

            _currentUnitOfWork.Pause();
         }
         catch (Exception)
         {
            _currentUnitOfWork.Abort();
            throw;
         }
      }
      #endregion

      public void Handle(SimpleTaskCreatedEvent item)
      {
         var newSimpleTask = _simpleTaskRepository.Get(item.Id);

         if (newSimpleTask != null)
         {
            View.Add(newSimpleTask.Id, newSimpleTask.Description);
         }
      }
   }
}